import sys
import sqlite3


def fetch(ref, label):
	#ref = sys.argv[1]
	conn = sqlite3.connect('/Users/jake.lin/local/apache-tomcat-6.0.35/webapps/ROOT/WEB-INF/cgi/sqlite/' + ref + '_ref.db')
	#if (len(sys.argv) == 3):
        #	label = sys.argv[2].upper()
	#fin = open("mart_export_mouse.txt", "r")
	c = conn.cursor()
	"""
Ensembl Gene ID Gene Start (bp) Gene End (bp)   Chromosome Name Description     EntrezGene ID   RefSeq mRNA [e.g. NM_001195597] UniProt Gene Name
ENSMUSG00000097066      65780905        65867305        13
ENSMUSG00000097793      81778773        81783749        13
ENSMUSG00000097374      57459572        57461553        19
8
	"""
	lc = 0
	if (label == ""):
		c.execute("select count(*) from " + ref + "_ref")
		print ref + " total count " + str(c.fetchone()[0])

	if (label != ""):
        	#c.execute("select * from " + ref + "_ref where ensn = " + label + " or gene_name = " + label  )
        	c.execute("SELECT chr, start, end, gene_name, ensn FROM " + ref + "_ref WHERE ensn = ? or rfsq = ? or gene_name = ? or entr = ?", (label, label, label, label))
        	results = c.fetchone()
		rc = "na"
        	if (results != None):
                	rc= label + ":" + results[3]
		return rc
	# We can also close the connection if we are done with it.
	# Just be sure any changes have been committed or they will be lost.
	conn.close()

def main(argv=None):
	if argv is None:
		argv = sys.argv
	if (len(argv) < 2):
		print "requires organism [label]"
		sys.exit()
	print "main"
	label = ""
	if (len(argv) == 3):
		label = argv[2]
	print (fetch(argv[1], label))
    		

def main2():
	print "main2"

if __name__ == "__main__":
	#main()
	print "fetch me"
